package cn.water.rocketmq.common;

import org.apache.rocketmq.client.consumer.DefaultLitePullConsumer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class MyConsumer {
    @Test
    public void consume01() throws MQClientException {
        //1.连接消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
        consumer.setConsumerGroup("test-group-01");
        consumer.setNamesrvAddr("localhost:9876");
        consumer.subscribe("test-topic-1","*");//消费者订阅消息
        //2.建立监听
        MessageListenerConcurrently messageListener = new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt messageExt = list.get(0);
                byte[] body = messageExt.getBody();
                String msg = new String(body, StandardCharsets.UTF_8);
                System.out.println("消费者01 收到消息:"+msg);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        };
        consumer.setMessageListener(messageListener);
        consumer.start();
        while(true);
    }
}
